<script setup lang="ts" name="Race">
import API from "@/api";
import { userinfo } from "@/store";
import RaceBar from "./RaceBar/index.vue";
import BetChoice from "./BetChoice/index.vue";
import BettingBill from "./BettingBill/index.vue";
const route = useRoute();
const { t } = useI18n();
const piniaUserinfo: any = userinfo();

const global: any = getCurrentInstance()?.appContext.config.globalProperties;

// 路线图可能状态
const statusList = [0, 43, 76, 100];

const data: any = reactive({
  activeTab: 0,
  mapStatusIndex: 0,
  lotteryList: [], //投注列表
  nowTime: "",
  routeParams: "",
  actCards: [], // 选择的投注
  isStartGame: false,
  betRecord: {
    record5: [],
    recordRank: [],
  }, // 投注记录
  showInstruction: false, // 中奖说明
  betChoiceRef: null,
});
let timer: any;

const {
  activeTab,
  mapStatusIndex,
  lotteryList,
  nowTime,
  routeParams,
  actCards,
  isStartGame,
  betRecord,
  showInstruction,
  betChoiceRef
} = toRefs(data);

// 是否显示重复投注
const isRepeat = computed(() => {
  return piniaUserinfo.getRaceRecent?.length > 0;
});

const nowDes: any = computed(() => {
  return {
    title1: t("rule.title54"),
    title1Content: t("rule.test16"),
    title2: t("rule.title55"),
    title2Content: t("rule.test17"),
  };
});

watch(
  () => actCards.value,
  (val) => {
    console.log("actCards", val);
  }
);

const mapStatus = computed(() => {
  return statusList[mapStatusIndex.value];
});

const computedActCards = computed(() => {
  const mergedData = Array.from(
    actCards.value
      ?.reduce((map: any, item: any) => {
        const { id, money } = item;
        const existingItem = map.get(id);
        if (existingItem) {
          // 如果 id 已存在，则将 money 相加
          existingItem.money += money;
        } else {
          // 否则，将当前项加入 Map
          map.set(id, { ...item });
        }
        return map;
      }, new Map())
      .values()
  );
  return mergedData;
});

const actCardsLen = computed(() => {
  return computedActCards.value.length;
});

const betTotal = computed(() => {
  return computedActCards.value
    ?.map((it: any) => +it.money)
    .reduce((a, b) => a + b, 0);
});

const balance = computed(() => {
  let all = computedActCards.value
    .map((item: any) => item.money)
    .reduce((a, b) => a + b, 0);
  return Number(piniaUserinfo.getUserMoney - all).toFixed(2);
});

const tabs = computed(() => {
  return [
    {
      title:  t("bet.bet21"),
      value: 0,
    },
    {
      title: t("bet.bet22"),
      value: 1,
    },
  ];
});

// 路线图状态修改
const handleMap = () => {
  mapStatusIndex.value++;
  if (mapStatusIndex.value >= 4) {
    mapStatusIndex.value = 0;
  }
};

// 倒计时
const startCountdown = () => {
  clearInterval(timer);
  timer = setInterval(() => {
    if (routeParams.value.betTime > 0) {
      routeParams.value.betTime--;
    } else {
      clearInterval(timer);
      // 倒计时结束后的操作
    }
  }, 1000); // 每秒执行一次
};

const setConfigData = (list: any) => {
  list.forEach((item: any) => {
    const str = item.type.split("_");
    let secondNum = +str[1];
    let thirdNum = +str[2];
    item.numbers = [...new Set([secondNum, thirdNum])];
  });
  lotteryList.value = list;
};

// 赛马历史记录
const getSmRecord = async () => {
  try {
    let res: any = await API.privateSmOrderListApi({
      planId: route?.query?.planId,
      typeConfigCode: route?.query?.typeConfigCode,
    });
    if (res) {
      betRecord.value = {
        record5: (res?.list as any) || [],
        recordRank: res?.nums || [],
      };
    }
  } catch (error) {}
};

// 获取初始化信息
const initRace = async (isNext?: boolean) => {
  try {
    let res = await API.lotteryPrivateAPI({
      planId: route?.query?.planId,
      typeConfigCode: route?.query?.typeConfigCode,
    });
    if (res?.code === 200) {
      if (!!isNext) {
        let data = res.data.periods[0];
        // 获取比赛结果，并开始赛马
        let winningNumber = data.winningNumber;
        routeParams.value = {
          ...routeParams.value,
          winningNumber,
        };
        mapStatusIndex.value = 0;
        nextTick(() => {
          isStartGame.value = true;
        });
      } else {
        isStartGame.value = false;
        let data = res.data.periods[0];
        // 本轮结束时间
        let timeInfo = Math.floor((data?.endTime - res?.data?.time) / 1000) + 1;
        // 本轮结束时间 - 本轮投注结束时间 时间差
        let timeRange = Math.floor((data?.endTime - data?.stopBetTime) / 1000);
        // 本轮投注结束时间
        let betTime =
          Math.floor((data?.stopBetTime - res?.data?.time) / 1000) + 1;
        // 上一场中奖数字
        let winningNumber = data.winningNumber;
        routeParams.value = {
          ...data,
          timeInfo,
          timeRange,
          betTime,
          winningNumber,
        };
        startCountdown();
        setConfigData(res.data.typeList);
      }
      console.log("routeParams.value", routeParams.value);
    }
  } catch (error) {}
};
watch(
  [() => route?.query?.planId, () => route?.query?.typeConfigCode],
  ([val1, val2]) => {
    if (val1 && val2) {
      initRace();
      getSmRecord();
    }
  },
  {
    immediate: true,
  }
);

// 提交
const submitBet = async () => {
  if (actCards.value?.length) {
    piniaUserinfo.setRaceRecent(actCards.value);
  }
  let betContent = computedActCards.value.map((item: any) => {
    return {
      money: item.money,
      content: item.type,
      name: item.name,
    };
  });
  if (betContent.length === 0) {
    piniaUserinfo.queryUserMoney();
    initRace(true);
    getSmRecord();
  } else {
    let params = {
      privateId: route?.query?.id,
      allMoney: betTotal.value,
      betContent: betContent,
      period: routeParams.value.period,
      bigCode: route?.query?.bigCode,
      typeConfigCode: route?.query?.typeConfigCode,
    };
    try {
      let res = await API.privateOrderBetApi(params);
      if (res?.code === 200) {
        initRace(true);
        getSmRecord();
      }
    } catch (error) {}
  }
};
watch(
  () => routeParams.value.betTime,
  (val) => {
    // 投注倒计时结束
    if (val <= 0) {
      // 提交投注信息并获取比赛结果
      submitBet();
    }
  },
  {
    immediate: true,
  }
);

// 开始新一轮
const getNewGame = () => {
  actCards.value = [];
  isStartGame.value = false;
  mapStatusIndex.value = 0;
  let timer: any;
  if (timer) {
    clearInterval(timer);
  }
  nextTick(() => {
    timer = setTimeout(() => {
      piniaUserinfo.queryUserMoney();
    }, 3000);
    initRace();
    getSmRecord();
  });
};

const handleBetAll = () => {
  betChoiceRef.value?.handleBetAll();
};

const handleBetRepeat = () => {
  betChoiceRef.value?.handleBetRepeat();
};

onBeforeUnmount(() => {
  clearInterval(timer); // 组件销毁前清除计时器
});
</script>

<template>
  <div class="raceWrap">
    <RaceBar
      :mapStatusIndex="mapStatusIndex"
      :isStart="isStartGame"
      :winningNumber="routeParams?.winningNumber"
      :time="routeParams?.betTime"
      :period="routeParams?.period"
      :betRecord="betRecord"
      :nextTime="routeParams?.timeRange"
      :timeInfo="routeParams?.timeInfo"
      :endTime="routeParams?.endTime"
      @getNewGame="getNewGame"
    />
    <div class="raceTabs">
      <div
        v-for="item in tabs"
        :key="item.value"
        class="raceTabItem"
        :class="{
          active: item.value === activeTab,
        }"
        @click="activeTab = item.value"
      >
        <span>{{ item.title }}</span>
        <span class="tips" v-if="actCardsLen && item.value === 1">{{
          actCardsLen
        }}</span>
      </div>
    </div>
    <BetChoice
      ref="betChoiceRef"
      v-if="activeTab === 0"
      :lotteryList="lotteryList"
      :isStart="isStartGame"
      :mapStatus="mapStatus"
      @handleMap="handleMap"
      v-model:actCards="actCards"
    />
    <BettingBill v-if="activeTab === 1" :actCards="computedActCards" />

    <div class="betAction">
      <div @click="showInstruction = true" class="winningRemark">
        <Iconfont
          name="icon-icon_shuoming"
          color="#FF6F1E"
          size="20"
          class="remarkIcon"
        /><span>{{ t("bet.test45") }}</span>
      </div>
      <van-button
        v-if="isRepeat"
        round
        class="reset"
        type="primary"
        :disabled="isStartGame"
        @click="handleBetRepeat"
        >{{ t("bet.test19") }}</van-button
      >
      <van-button :disabled="isStartGame" @click="handleBetAll" round class="bet" type="primary">
        {{ t("bet.test20") }}
      </van-button>
    </div>
    
    <van-popup
      v-model:show="showInstruction"
      round
      position="bottom"
      class="confirmBetPop"
    >
      <div class="popTitle">
        <div>{{ t("bet.test45") }}</div>
        <Iconfont
          @click="showInstruction = false"
          class="closeIcon"
          name="icon-icon_close"
          color="#FF2D55"
          size="20"
        />
      </div>
      <div class="remarkContent">
        <div class="titleName">{{ nowDes?.title1 }}</div>
        <div class="contentDetail">{{ nowDes?.title1Content }}</div>
        <div class="titleName">{{ nowDes?.title2 }}</div>
        <div class="contentDetail">{{ nowDes?.title2Content }}</div>
      </div>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
@import url("./index.scss");
</style>
